package com.lagou.service.impl;

import com.lagou.entity.Order;
import com.lagou.repository.OrderRepository;
import com.lagou.service.OrderService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public boolean order(Order order) {

        //检查库存
        Integer goodsCount = redisTemplate.opsForValue().get("goods_count");
        if (goodsCount <= 0) {
            System.out.println("商品已售罄。。。");
            return false;
        }

        order.setOrderId(UUID.randomUUID().toString());
        order.setOrderStatus("待支付");

        rocketMQTemplate.asyncSend("tp_order", order, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

            }

            @Override
            public void onException(Throwable e) {
                e.printStackTrace();
            }
        });
        return true;
    }

    @Override
    public String pay(String orderId) {
        Order order = orderRepository.findById(orderId).get();
        if (order.getOrderStatus().equals("待支付")) {
            order.setOrderStatus("已支付");
            orderRepository.save(order);

            return "支付成功";
        }

        return order.getOrderStatus();
    }
}
